/**
 * 数据摘要显示插件，样式如百度，Google相似
 * @author Ly
 * @version 1.0a
 */
/**
 * 摘要显示插件构造函数
 * @param {Object} container 当前
 * @param {Object} config 配置信息
 * config = {
	 width : '100%',           // 宽度，默认100%
	 lineHeight : 20           // 段落间的间距，默认20像素
	 events : {
		 onclick : function(data) {}  // obj的属性包含传入的对象
	 }
 }
 */
Ly.DataDigest = function(container /* Object */, config /* Object */) {
	var _this = this;
	
	config = config || {};
	
	this.config = {
		id : 'ly-datadigest-' + Ly.getCount(),
		// DataDigest插件容器
		container : container || document.body,
		// DataDigest插件宽度
		width : config.width || '100%',
		// 段落间隔
		lineHeight : config.lineHeight || 20,
		// 公共事件集合
		events : config.events || {},
		// 数据块列表
		dataBlockList : [],
		// 翻页工具条信息
		pageInfo : {},
		// 数源源
		dataSource : [],
		// 添加事件的对象
		objList : []
	};
	this.private = {
        /**
         * 存储用Ly.addEvent来添加事件的对象
         * @param {Object} obj 被添加事件的对象
         */
        saveObj : function(obj) {
            var	c = _this.config,
            	oll = c.objList.length;
            
            for (var i = 0; i < oll; i++) {
                if (c.objList[i] === obj) {
                    return;
                }
            }
            c.objList.push(obj);
			return this;
        },
		/**
		 * 创建数据块，组成DataDigest插件的基础
		 * @param {Object} data 数据源
		 * data = {
			 title : '标题',
			 content : '内容',
			 property : ['属性1', '属性2'],
			 displayType : 'vertical',
			 events : {
				 onclick : function(data) { } // 事件集合，当前数据块对象
			 },
			 disabledPublicEvents : false // 是否禁用公共事件，默认false
		   }
		 */
		createDataBlock : function(data /* Object */) {
			var _subContainer = Ly.createElement('div', {
					cls : 'ly-datadigest-datablock-container',
					width : _this.config.width,
					style : 'margin-bottom:' + _this.config.lineHeight + 'px;'
				}),
				_title = Ly.createElement('div', {
					cls : 'ly-datadigest-datablock-title-container'
				}),
				_prefix = Ly.createElement('span', {
					cls : 'ly-datadigest-datablock-title-prefix'
				}),
				_titleContent = Ly.createElement('span', {
					cls : 'ly-datadigest-datablock-title-content'
				}),
				_content = Ly.createElement('div', {
					cls : 'ly-datadigest-datablock-content'
				}),
				_property = Ly.createElement('div', {
					cls : 'ly-datadigest-datablock-property'
				});
			
			if (_this.config.pageInfo.container) {
				_this.config.container.insertBefore(_subContainer, _this.config.pageInfo.container);
			} else {
				_this.config.container.appendChild(_subContainer);
			}
			_subContainer.appendChild(_title);
			_subContainer.appendChild(_content);
			_subContainer.appendChild(_property);
			_title.appendChild(_prefix);
			_title.appendChild(_titleContent);
			
			_prefix.innerHTML = data.prefix;
			_titleContent.innerHTML = data.title;
			_content.innerHTML = data.content;
			
			for (var i = 0, len = data.property.length; i < len; ++i) {
				var p = Ly.createElement('div', {
						style : 'display:' + (data.displayType.toLowerCase() == 'vertical' ? 'block' : 'inline')
					});
				p.innerHTML = data.property[i];
				_property.appendChild(p);
				p = null;
			}
			//_this.config.container.appendChild(_subContainer);
			
			// 初始化标题的公共事件集合
			if (!data.disabledPublicEvents) {
				for (var p in _this.config.events) {
					Ly.addEvent(p, function(obj) { _this.config.events[p](data); }, _titleContent);
				}
			}
			// 初始化标题的私有事件
			for (var p in data.events) {
				Ly.addEvent(p, function(obj) { data.events[p](data); }, _titleContent);
			}
			// 缓存数据存，用于更新
			_this.config.dataBlockList.push(_subContainer);
			return _this;
		},
		/**
		 * 删除数据块
		 * @param {Object} dataBlock 数据块对象
		 */
		removeDataBlock : function(dataBlock /* Number */) {
			if (!dataBlock || dataBlock == null) {
				alert('要删除的数据块不合法！');
				return false;
			}
			var _childNodes = dataBlock.childNodes;
			for (var i = _childNodes.length - 1; i >= 0; --i) {
				dataBlock.removeChild(_childNodes[i]);
				_childNodes[i] = null;
			}
			dataBlock.parentNode.removeChild(dataBlock);
			
			for (var i = 0, len = _this.config.dataBlockList.length; i < len; ++i) {
				if (_this.config.dataBlockList[i] === dataBlock) {
					_this.config.dataBlockList.splice(i, 1);
					break;
				}
			}
			
			dataBlock = null;
			return _this;
		},
		/**
		 * 创建翻页工具条
		 */
		createPagingToolBar : function() {
			if (typeof _this.config.pageInfo.position == 'undefined') {
				return _this;
			}
			
			_this.config.pageInfo.container = Ly.createElement('div', {
				cls : 'ly-datadigest-pagingtoolbar-container'
			});
			var _pageInfo = _this.config.pageInfo,
				_first = Ly.createElement('div', {
					id : _this.config.id + '-first',
					cls : 'ly-datadigest-pagingtoolbar-pagecode'
				}),
				_previous = Ly.createElement('div', {
					id : _this.config.id + '-previous',
					cls : 'ly-datadigest-pagingtoolbar-pagecode'
				}),
				_next = Ly.createElement('div', {
					id : _this.config.id + '-next',
					cls : 'ly-datadigest-pagingtoolbar-pagecode'
				}),
				_last = Ly.createElement('div', {
					id : _this.config.id + '-last',
					cls : 'ly-datadigest-pagingtoolbar-pagecode'
				}),
				_inputBoxContainer = Ly.createElement('div', {
					id : _this.config.id + '-input-container',
					cls : 'ly-datadigest-pagingtoolbar-inputbox-container'
				}),
				_rs = Ly.createElement('div', {
					id : _this.config.id + '-rs',
					cls : 'ly-datadigest-pagingtoolbar-page'
				});
				_page = Ly.createElement('div', {
					id : _this.config.id + '-page',
					cls : 'ly-datadigest-pagingtoolbar-page'
				});
				_msg = Ly.createElement('div', {
					id : _this.config.id + '-msg',
					cls : 'ly-datadigest-pagingtoolbar-msg'
				});
			_first.innerHTML = '|&lt;';
			_previous.innerHTML = '&lt;&lt;';
			_next.innerHTML = '&gt;&gt;';
			_last.innerHTML = '&gt;|';
			_inputBoxContainer.innerHTML = '<input type="text" ' +
				'id="' + _this.config.id + '-input" ' +
				'name="' + _this.config.id + '-input" ' +
				'class="ly-datadigest-pagingtoolbar-inputbox" />';
			
			_rs.innerHTML = _pageInfo.rsCount;
			_page.innerHTML = _pageInfo.currentPage + '/' + _pageInfo.pageCount;
			
			_rs.title = '共' + _pageInfo.rsCount + '条记录';
			_page.title = '第' + _pageInfo.currentPage + '页，共' + _pageInfo.pageCount + '页';
			
			if (typeof _pageInfo.msg != 'undefined') {
				_msg.innerHTML = _pageInfo.msg;
			} else {
				_msg.style.display = 'none';
			}
			
			_this.config.container.appendChild(_pageInfo.container);
			_pageInfo.container.appendChild(_rs);
			_pageInfo.container.appendChild(_page);
			_pageInfo.container.appendChild(_first);
			_pageInfo.container.appendChild(_previous);
			_pageInfo.container.appendChild(_next);
			_pageInfo.container.appendChild(_last);
			_pageInfo.container.appendChild(_inputBoxContainer);
			_pageInfo.container.appendChild(_msg);
			
			_this.private.appendPageCode(_next);
			_this.private.appendPrivateEventToPagingToolBar(_this.config.id);
			return _this;
		},
		/**
		 * 给翻页工具条添加页码，并添加到obj前面
		 * @param {Object} obj 参照对象
		 */
		appendPageCode : function(obj /* Object */) {
            var pi = _this.config.pageInfo,
                cp = parseInt(pi.currentPage),
                pc = parseInt(pi.pageCount),
                start = 0,
                end = pc;
            
            start = (cp - 5) < 1 ? 1 : cp - 5;
            
			// 大於總頁
            if (start + 9 > pc) {
                end = pc;
                start = parseInt(pc - 9) < 1 ? 1 : pc - 9;    // 修正起始頁
            } else {
                end = start + 9;
            }
            
            for (var i = start; i <= end; i++) {
                var p = Ly.createElement('div', {
                        id : _this.config.id + '-' + i
                    });
                obj.parentNode.insertBefore(p, obj);
                p.innerHTML = i;
                
                if (i == cp ) {
                    p.className = 'ly-datadigest-pagingtoolbar-pagecode-focus';
                } else {
                    p.className = 'ly-datadigest-pagingtoolbar-pagecode';
                    Ly.addEvent('onmouseover',
                        function(obj) {
                            obj.className = 'ly-datadigest-pagingtoolbar-pagecode-focus';
                        },
                        p);
                    Ly.addEvent('onmouseout',
                        function(obj) {
                            obj.className = 'ly-datadigest-pagingtoolbar-pagecode';
                        },
                        p);
                }
                Ly.addEvent(Ly.Event.ONCLICK,
                    function(obj) {
                        _this.config.pageInfo.currentPage = parseInt(obj.innerHTML);
                        _this.private.updatePagingToolBar();
                        _this.config.pageInfo.behavior(_this.config.pageInfo.currentPage);
                    },
                    p);
                this.saveObj(p);
				p = null;
            }
			return _this;
		},
		/**
		 * 给翻页工具条添加私有事件
		 */
		appendPrivateEventToPagingToolBar : function(id /* String */) {
            var _first = Ly.get(id + '-first'),
                _previous = Ly.get(id + '-previous'),
                _next = Ly.get(id + '-next'),
                _last = Ly.get(id + '-last'),
                _input = Ly.get(id + '-input');
            
            this.appendPublicEventToPagingToolBar(_first);
            this.appendPublicEventToPagingToolBar(_previous);
            this.appendPublicEventToPagingToolBar(_next);
            this.appendPublicEventToPagingToolBar(_last);
            
            document.onkeydown = function(event) {
                var e=event || window.event,
                	keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
                
                if (keyCode == 0x0D){
                    var srcElement = e.srcElement || e.target;
                    
                    if (srcElement.id == _this.config.id + '-input'){
                        var
                            value = parseInt(Ly.get(_this.config.id + '-input').value),
                            pi = _this.config.pageInfo;
                        
						if (!Ly.isInt(value)) {
							alert('请输入合法的页码!');
							Ly.get(_this.config.id + '-input').value = '';
							return false;
						}
                        value = parseInt(value);
                        if (value < 1) {
                            value = 1;
                        }
                        if (value > pi.pageCount) {
                            value = pi.pageCount;
                        }
                        pi.currentPage = value;
                        pi.behavior(value);
                        Ly.get(_this.config.id + '-input').value = '';
                        _this.private.updatePagingToolBar();
                    }   
                }   
            };
            Ly.addEvent(Ly.Event.ONCLICK,
                function(obj) {
                    var pi = _this.config.pageInfo;
                    pi.currentPage = 1;
                    pi.behavior(1);
                    _this.private.updatePagingToolBar();
                },
                _first);
            Ly.addEvent(Ly.Event.ONCLICK,
                function(obj) {
                    var pi = _this.config.pageInfo;
                    
                    pi.currentPage = --pi.currentPage < 1 ? 1 : pi.currentPage;
                    pi.behavior(pi.currentPage);
                    _this.private.updatePagingToolBar();
                },
                _previous);
            Ly.addEvent(Ly.Event.ONCLICK,
                function(obj) {
                    var pi = _this.config.pageInfo;
                    
                    pi.currentPage = ++pi.currentPage > pi.pageCount ? pi.pageCount : pi.currentPage;
                    _this.config.pageInfo.behavior(pi.currentPage);
                    _this.private.updatePagingToolBar();
                },
                _next);
            Ly.addEvent(Ly.Event.ONCLICK,
                function(obj) {
                    var pi = _this.config.pageInfo;
                    
                    pi.currentPage = pi.pageCount;
                    pi.behavior(pi.pageCount);
                    _this.private.updatePagingToolBar();
                },
                _last);
            this.saveObj(_first);
            this.saveObj(_previous);
            this.saveObj(_next);
            this.saveObj(_last);
			_first = null;
			_previous = null;
			_next = null;
			_last = null;
			_input = null;
			return this;
		},
		/**
		 * 给翻页工具条添加公共事件
		 * @param {Object} obj 要添加公共事件的元素
		 */
		appendPublicEventToPagingToolBar : function(obj /* Object */) {
            Ly.addEvent(Ly.Event.ONMOUSEOVER,
                function(obj) {
                    obj.className = 'ly-datadigest-pagingtoolbar-pagecode-focus';
                },
                obj);
            Ly.addEvent(Ly.Event.ONMOUSEOUT,
                function(obj) {
                    obj.className = 'ly-datadigest-pagingtoolbar-pagecode';
                },
                obj);
            this.saveObj(obj);
			return this;
		},
		/**
		 * 更新翻页工具条
		 */
		updatePagingToolBar : function() {
			if (typeof _this.config.pageInfo.container == 'undefined') {
				return this;
			}
            var _pageInfo = _this.config.pageInfo,
				_container = _pageInfo.container,
				ns = _container.childNodes,
				arr = ['first', 'previous', 'next', 'last'],
				c = _this.config,
                id = c.id,
                pi = c.pageInfo,
                rc = pi.rsCount,
                cp = pi.currentPage,
                pc = pi.pageCount;
            
			for (var i = ns.length - 1; i >= 0; --i) {
				_container.removeChild(ns[i]);
				//ns[i] = null;
				for (var j = 0, len2 = c.objList.length; j < len2; ++j) {
					if (c.objList[j] === ns[i]) {
						c.objList[j] = null;
						c.objList.splice(j, 1);
						break;
					}
				}
			}
			
			
			var _first = Ly.createElement('div', {
					id : _this.config.id + '-first',
					cls : 'ly-datadigest-pagingtoolbar-pagecode'
				}),
				_previous = Ly.createElement('div', {
					id : _this.config.id + '-previous',
					cls : 'ly-datadigest-pagingtoolbar-pagecode'
				}),
				_next = Ly.createElement('div', {
					id : _this.config.id + '-next',
					cls : 'ly-datadigest-pagingtoolbar-pagecode'
				}),
				_last = Ly.createElement('div', {
					id : _this.config.id + '-last',
					cls : 'ly-datadigest-pagingtoolbar-pagecode'
				}),
				_inputBoxContainer = Ly.createElement('div', {
					id : _this.config.id + '-input-container',
					cls : 'ly-datadigest-pagingtoolbar-inputbox-container'
				}),
				_rs = Ly.createElement('div', {
					id : _this.config.id + '-rs',
					cls : 'ly-datadigest-pagingtoolbar-page'
				});
				_page = Ly.createElement('div', {
					id : _this.config.id + '-page',
					cls : 'ly-datadigest-pagingtoolbar-page'
				});
				_msg = Ly.createElement('div', {
					id : _this.config.id + '-msg',
					cls : 'ly-datadigest-pagingtoolbar-msg'
				});
			_first.innerHTML = '|&lt;';
			_previous.innerHTML = '&lt;&lt;';
			_next.innerHTML = '&gt;&gt;';
			_last.innerHTML = '&gt;|';
			_inputBoxContainer.innerHTML = '<input type="text" ' +
				'id="' + _this.config.id + '-input" ' +
				'name="' + _this.config.id + '-input" ' +
				'class="ly-datadigest-pagingtoolbar-inputbox" />';
			
			_rs.innerHTML = _pageInfo.rsCount;
			_page.innerHTML = _pageInfo.currentPage + '/' + _pageInfo.pageCount;
			
			_rs.title = '共' + _pageInfo.rsCount + '条记录';
			_page.title = '第' + _pageInfo.currentPage + '页，共' + _pageInfo.pageCount + '页';
			
			if (typeof _pageInfo.msg != 'undefined') {
				_msg.innerHTML = _pageInfo.msg;
			} else {
				_msg.style.display = 'none';
			}
			
			_this.config.container.appendChild(_pageInfo.container);
			_pageInfo.container.appendChild(_rs);
			_pageInfo.container.appendChild(_page);
			_pageInfo.container.appendChild(_first);
			_pageInfo.container.appendChild(_previous);
			_pageInfo.container.appendChild(_next);
			_pageInfo.container.appendChild(_last);
			_pageInfo.container.appendChild(_inputBoxContainer);
			_pageInfo.container.appendChild(_msg);
			
			_this.private.appendPageCode(_next);
			_this.private.appendPrivateEventToPagingToolBar(_this.config.id);
			return this;
		},
		// 更新数据视图
		updateDataView : function() {
           var _dataBlockList = _this.config.dataBlockList;
		   // 删除原有的数据块
		   for (var i = _dataBlockList.length - 1; i >= 0; --i) {
			   this.removeDataBlock(_dataBlockList[i]);
		   }
		   
		   // 用dataSource中的数据再次生成所有的数据块
		   for (var i = 0, len = _this.config.dataSource.length; i < len; ++i) {
			   this.createDataBlock(_this.config.dataSource[i]);
		   }
		   return this;
		}
	};
};
Ly.DataDigest.prototype = {
	ver : '1.0a',
	/**
	 * 绑定数据
	 * @param {Array} 数据体
	 * data = [{
			prefix : '標題前缀',
			title : '标题',
			content : '内容',
			property : ['属性1', '属性2'],
			displayType : 'vertical'       // 属性的显示方式，horizontal/vertical
			events : {
				onclick : function(data) {} // data为数据块对象，包含所有的传入属性
			},
			disabledPublicEvents : false // 是否禁用公共事件，默认false
		}, {
	   }];
	 */
	bind : function(data /* Array */) {
		var _msg, _data = [];
		
		data = data || [];
		
		for (var i = 0, len = data.length; i < len; ++i) {
			if (Ly.isEmpty(data[i])) { continue; }
			/** 允许标题与内容为空
			data[i].title = data[i].title || '';
			data[i].content = data[i].content || '';
			_msg = [];
			if (data[i].title == '') {
				_msg.push('标题');
			}
			if (data[i].content == '') {
				_msg.push('内容');
			}
			if (_msg != '') {
				alert('第 ' + i + ' 条数据不合法，' + _msg.join('与') + '为空！');
				continue;
			}
			*/
			_data.push({
				prefix      : data[i].prefix || '',
				title       : data[i].title || '',
				content     : data[i].content || '',
				property    : data[i].property || [],
				displayType : data[i].displayType || 'vertical',
				events      : data[i].events || {},
				disabledPublicEvents : data[i].disabledPublicEvents
			});
		}
		this.config.dataSource = _data;
		return this;
	},
	/**
	 * 添加翻页工具条
	 * @param {Object} config 翻页工具条配置信息
	 * config = {
           position: 'bottom',
           rsCount : 0,
           pageSize : 15,
           currentPage : 1,
           pageCount : 50,
		   msg : '信息',
           behavior : function(obj) {}
	 }
	 */
	pagingToolBar : function(config /* Object */) {
		config = config || {};
		this.config.pageInfo = {
			position    : config.position || 'bottom',
			rsCount     : config.rsCount || 0,
			pageSize    : config.pageSize || 15,
			currentPage : config.currentPage || 1,
			pageCount   : config.pageCount || 0,
			msg         : config.msg,
			behavior    : config.behavior || function() {}
		};
		return this;
	},
	// 渲染插件
	render : function() {
		this.private.updateDataView();
		this.private.createPagingToolBar();
		return this;
	},
	/**
	 * 更新翻页工具条
	 * @param {Object} config 翻页工具条配置信息
	 * config = {
           position: 'bottom',
           rsCount : 0,
           pageSize : 15,
           currentPage : 1,
           pageCount : 50,
           themes : 'default',
           msg : '',
           behavior : function(obj) {}
	 }
	 */
	updatePagingToolBar : function(config /* Object */) {
		var _pageInfo = this.config.pageInfo;
		config = config || {};
		this.config.pageInfo = {
			container : _pageInfo.container,
			position : config.position || _pageInfo.position,
			rsCount : config.rsCount || _pageInfo.rsCount,
			pageSize : config.pageSize || _pageInfo.pageSize,
			currentPage : config.currentPage || _pageInfo.currentPage,
			pageCount : config.pageCount || _pageInfo.pageCount,
			behavior : config.behaior || _pageInfo.behavior
		};
		this.private.updatePagingToolBar();
		return this;
	},
	/**
	 * 更新数据视图
	 * @param {Array} data 用来更新的数据源，若省略则使用原有数据
	 */
	updateDataView : function(data /* Array */) {
		data = data || [];
		this.bind(data);
		this.private.updateDataView();
		return this;
	},
	/**
	 * 删除数据块
	 * @param {Number} index 要删除的数据块的索引，从零开始，省略则删除所有
	 */
	 removeDataBlock : function(index /* Number */) {
		 var _dataBlock = this.config.dataBlockList;
		 if (typeof index == 'undefined') {
			 for (var i = _dataBlock.length - 1; i >= 0; --i) {
				 this.private.removeDataBlock(_dataBlock[i]);
			 }
		 } else {
			 if (index < 0 || index >= _dataBlock.length) {
				 alert('要删除的数据块索引参数不合法！');
			 }
		 }
		 return this;
	 }
};